// https://www.programmercarl.com/%E9%9D%A2%E8%AF%95%E9%A2%9802.07.%E9%93%BE%E8%A1%A8%E7%9B%B8%E4%BA%A4.html#%E6%80%9D%E8%B7%AF
// https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/description/


// 注意不能修改原链表，所以需要使用代替节点来操作不能直接使用head
// 获取两个链表的长度 使用长度差让长的先走 再两个一起走判断节点是否相等
const getIntersectionNode = function (headA, headB) {
  // 方法函数 获取每个链表的长度
  const getLength = (head) => {
    let length = 0;
    let cur = head;
    while (cur) {
      cur = cur.next;
      length++;
    }
    return length;
  };
  let curA = headA,
    curB = headB;
  let lengthA = getLength(headA);
  let lengthB = getLength(headB);
  let length = lengthA - lengthB;
  // A长的情况下A先走
  // 使用长度查的正负来判断哪个厂
  if (length > 0) {
    while (length) {
      curA = curA.next;
      length--;
    }
  } else if (length < 0) {
    // B长的情况下B先走
    while (Math.abs(length)) {
      curB = curB.next;
      length++;
    }
  }
  while (curA && curB) {
    if (curA === curB) {
      return curA;
    }
    curA = curA.next;
    curB = curB.next;
  }
  return null;
};
